<template>
  <el-upload
    ref="upload"
    class="imageUpload"
    name="file"
    :auto-upload="false"
    :action="baseUrl + '/upload'"
    :headers="{ 'Authorization': token }"
    :multiple="false"
    :list-type="!src?'picture-card':'picture'"
    :show-file-list="false"
    :on-change="onUploadChange"
    :on-success="onUploadSuccess"
  >
    <el-image v-if="src" :src="!showImgUrl?baseUrl+src:showImgUrl" />
    <i v-else class="el-icon-plus" />
  </el-upload>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  name: 'ImageUpload',
  props: {
    src: {
      type: String,
      require: false,
      default: undefined
    }
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      showImgUrl: undefined,
      isUploadSuccess: false
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  methods: {
    onUploadChange(value) {
      this.showImgUrl = value.url
    },
    onUploadSuccess(value) {
      this.$emit('onUploadSuccess', value)
      this.showImgUrl = value.data.imageUrl
      this.isUploadSuccess = true
    },
    submit() {
      if (this.showImgUrl) this.$refs.upload.submit()
      else this.$emit('onUploadSuccess')
    }
  }
}
</script>

<style lang="scss" scoped>
.imageUpload {
  .el-image {
    width: 100px;
    height: 100px;
    transition: all 0.1s;
    border-radius: 50%;
    &:hover {
      box-shadow: 0 0 5px black;
    }
  }
}
</style>
